package com.jucai.pppeiyouclient.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.bean.PayTypeBean;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.dialog.Balance2CoinDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class WalletDetailActivity extends BaseActivity {
    private static final String TAG = "WalletDetailActivity : ";
    private TextView walletBalance, walletFrozen, walletGoldCount, walletBalanceToGold, walletBindCard,
            walletMyGold, walletRedPackage, walletCoupon, walletMerchantService, walletTransactionRecord,
            walletRecharge, walletWithdrawals;
    private String balance, coin, frozenBalance;
    private Balance2CoinDialog balance2CoinDialog;
    private EditText coinText;
    private int coinSum = 0;
    private float balanceSum = 0;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_wallet_detail);

        ((TextView) findViewById(R.id.common_title_text)).setText("钱包");
        walletBalance = (TextView) findViewById(R.id.wallet_balance);
        walletFrozen = (TextView) findViewById(R.id.wallet_frozen);
        walletGoldCount = (TextView) findViewById(R.id.wallet_gold_count);
        walletBalanceToGold = (TextView) findViewById(R.id.wallet_balance_to_gold);
        walletBindCard = (TextView) findViewById(R.id.wallet_bind_card);
        walletMyGold = (TextView) findViewById(R.id.wallet_my_gold);
        walletTransactionRecord = (TextView) findViewById(R.id.wallet_transaction_record);
        walletRedPackage = (TextView) findViewById(R.id.wallet_red_package);
        walletCoupon = (TextView) findViewById(R.id.wallet_coupon);
        walletMerchantService = (TextView) findViewById(R.id.wallet_merchant_service);
        walletRecharge = (TextView) findViewById(R.id.wallet_recharge);
        walletWithdrawals = (TextView) findViewById(R.id.wallet_withdrawals);
        balance2CoinDialog = new Balance2CoinDialog(WalletDetailActivity.this);
        coinText = (EditText) balance2CoinDialog.findViewById(R.id.dialog_coin_sum);
    }

    @Override
    protected void initData() {
        walletBalanceToGold.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        coinSum = Integer.valueOf(balance2CoinDialog.getCoinSum());
        balanceSum = Float.valueOf(walletBalance.getText().toString());
    }

    @Override
    protected void loadNetData() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Client_Wallet.getBalance");
        CommonRequestNetData.getJsonObjectData(WalletDetailActivity.this, param, true, new CommonRequestNetData.JsonObjectCallBack() {
            @Override
            public void parseJsonObject(JSONObject jsonObject) {
                LogUtils.e(TAG + "jsObj = " + jsonObject);
                try {
                    balance = jsonObject.getString("member_balance");
                    coin = jsonObject.getString("member_coin");
                    frozenBalance = jsonObject.getString("member_frozen_balance");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            walletBalance.setText(balance);
                            walletGoldCount.setText(coin);
                            walletFrozen.setText("已冻结：¥" + frozenBalance);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
        walletBalanceToGold.setOnClickListener(this);
        walletBindCard.setOnClickListener(this);
        walletMyGold.setOnClickListener(this);
        walletTransactionRecord.setOnClickListener(this);
        walletRedPackage.setOnClickListener(this);
        walletCoupon.setOnClickListener(this);
        walletMerchantService.setOnClickListener(this);
        walletRecharge.setOnClickListener(this);
        walletWithdrawals.setOnClickListener(this);
        balance2CoinDialog.setOnclickListener(this);
        walletBalance.setOnClickListener(this);
        walletGoldCount.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(WalletDetailActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.wallet_balance:
                startActivity(new Intent(WalletDetailActivity.this, TransactionRecordActivity.class));
                break;

            case R.id.wallet_balance_to_gold:
                balance2CoinDialog.show();
                break;

            case R.id.wallet_bind_card:
                getInfoVercation();
                //startActivity(new Intent(WalletDetailActivity.this, BindBankCardActivity.class));
                break;

            case R.id.wallet_my_gold:
                startActivity(new Intent(WalletDetailActivity.this, CoinRecordActivity.class));
                break;

            case R.id.wallet_transaction_record:
                startActivity(new Intent(WalletDetailActivity.this, TransactionRecordActivity.class));
                break;

            case R.id.wallet_red_package:
                HashMap<String, String> param = new HashMap<>();
                param.put("service", "Redpacket_Redpacket.getIndexURL");

                CommonRequestNetData.getJsonObjectData(WalletDetailActivity.this, false, param, new CommonRequestNetData.JsonObjectCallBack() {
                    @Override
                    public void parseJsonObject(JSONObject jsonObject) {
                        LogUtils.e(TAG + "jsObj = " + jsonObject);
                        try {
                            String url = jsonObject.getString("accompany_index");
                            CommonH5Activity.startCommH5(WalletDetailActivity.this, 3, url, null, null, null);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                break;

            case R.id.wallet_coupon:
                startActivity(new Intent(WalletDetailActivity.this, WalletCouponActivity.class));
                break;

            case R.id.wallet_merchant_service:
                startActivity(new Intent(WalletDetailActivity.this, MerchantServiceActivity.class));
                break;

            case R.id.wallet_recharge:
                startActivity(new Intent(WalletDetailActivity.this, RechargeActivity.class));
                break;

            case R.id.wallet_withdrawals:
//                startActivity(new Intent(WalletDetailActivity.this, WithdrawsActivity.class));
                getCarData();
                break;

            case R.id.dialog_coin_minus:
                try {
                    coinSum = Integer.parseInt(coinText.getText().toString().trim());
                } catch ( Exception e) {
                    e.printStackTrace();
                    return;
                }
                if (coinSum == 0) {
                    ToastUtils.showToast("兑换数量不能小于0");
                } else {
                    --coinSum;
                    coinText.setText(coinSum + "");
                }
                break;

            case R.id.dialog_coin_add:
                try {
                    coinSum = Integer.parseInt(coinText.getText().toString().trim());
                } catch ( Exception e) {
                    e.printStackTrace();
                    return;
                }
                ++coinSum;
                coinText.setText(coinSum + "");
                break;

            case R.id.dialog_sure_change:
                try {
                    coinSum = Integer.parseInt(coinText.getText().toString().trim());
                } catch ( Exception e) {
                    e.printStackTrace();
                    return;
                }
                balanceSum = Float.valueOf(walletBalance.getText().toString());
                LogUtils.d(coinSum + "|" + balanceSum);
                if (coinSum == 0) {
                    ToastUtils.showToast("转换数量不能为0");
                } else if (coinSum > balanceSum) {
                    ToastUtils.showToast("余额不足");
                } else {
                    HashMap<String, String> coinParam = new HashMap<>();
                    coinParam.put("service", "Client_Wallet.BalanceToCoin");
                    coinParam.put("credit", coinText.getText().toString());

                    CommonRequestNetData.getJsonString(WalletDetailActivity.this, false, coinParam, new CommonRequestNetData.JsonStringCallBack() {
                        @Override
                        public void parseJsonString(String str) {
                            LogUtils.e(TAG + str);
                            ToastUtils.showToast("转换成功");
                            coinSum = 0;
                            coinText.setText("0");
                            loadNetData();
                        }
                    });
                }
                balance2CoinDialog.dismiss();
                break;

            case R.id.wallet_gold_count:
                startActivity(new Intent(WalletDetailActivity.this, CoinRecordActivity.class));
                break;

            default:
                break;
        }
    }

    private void getCarData() {
        Map<String, String> mapRegister = new HashMap<>();
        mapRegister.put("service", "Client_CreditCard.getAccount");
        mapRegister.put("token", LoginUtils.getToken(this));
        mapRegister.put("member_id", LoginUtils.getMember_id(this));
        CommonRequestNetData.getJsonString(this, true, mapRegister, new CommonRequestNetData.JsonStringCallBack() {
            @Override
            public void parseJsonString(String str) {
                PayTypeBean payTypeBean = new Gson().fromJson(str, PayTypeBean.class);
                if (payTypeBean != null && payTypeBean.getCredit_info() != null && payTypeBean.getCredit_info().size() > 0) {
                    Intent intent = new Intent(WalletDetailActivity.this, WithdrawsActivity.class);
                    intent.putExtra("type", 0);
                    intent.putExtra("cars", payTypeBean);
                    startActivityForResult(intent, 1001);

                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(WalletDetailActivity.this).setTitle("提示").setMessage("您还没设置银行卡！").setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(WalletDetailActivity.this, BindBankCardActivity.class));
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }
            }
        });
    }

    private void getInfoVercation() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Apply.getLastInfo");
        param.put("member_id", LoginUtils.getMember_id(this));
        param.put("token", LoginUtils.getToken(this));
        CommonRequestNetData.getJsonObjectData(WalletDetailActivity.this, param, true, new CommonRequestNetData.JsonObjectCallBack() {
            @Override
            public void parseJsonObject(JSONObject jsonObject) throws Exception {
                LogUtils.e(TAG + "jsObj = " + jsonObject.toString());
                int memberApplyStatus = Integer.parseInt(jsonObject.getString("member_apply_status"));////审核状态 0 未审核 1通过 -1未通过 -2 未提交
                /*if(memberApplyStatus == 0){
                    ToastUtils.showToast("您的实名验证还在审核中，请审核通过后再绑定银行卡！");
                }else */if(memberApplyStatus == 1){
                    startActivity(new Intent(WalletDetailActivity.this, BindBankCardActivity.class));
                }else {
                    showDialogNoVer();
                }
            }

        });
    }
    public void showDialogNoVer(){
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(WalletDetailActivity.this);
        builder.setMessage("您还未通过实名认证，现在去添加认证吗？");
        builder.setTitle("提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(WalletDetailActivity.this, RegisterThirdStepActivity.class);
                intent.putExtra("type",2);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
}
